package com.chineseall.app.ws;

import java.io.IOException;
import java.util.Set;

import javax.websocket.SendHandler;
import javax.websocket.SendResult;
import javax.websocket.Session;

import jmind.core.support.LogUtil;

import com.chineseall.app.ConnectionManager;
import com.chineseall.app.pojo.mongo.MMessage;

public class SendMessage {

    public static boolean send(Session session, MMessage message) {
        try {
            if (session != null && session.isOpen()) {

                session.getBasicRemote().sendText(message.toString());
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void sendAsyc(final Session session, MMessage message) {
        session.getAsyncRemote().sendText(message.toString(), new SendHandler() {

            @Override
            public void onResult(SendResult result) {
                if (!result.isOK()) {
                    try {
                        session.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    result.getException().printStackTrace();
                }

            }

        });
    }

    public static boolean send(int uid, MMessage message) {
        WebSocketEndpoint socketEndpoint = ConnectionManager.INSTANCE.getSession(uid);
        if (socketEndpoint == null) {
            return false;
        }
        Session session = socketEndpoint.session;
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message.toString());
                return true;
            } catch (IOException e) {
                LogUtil.err(socketEndpoint + "send msg err ,ws=" + e.getMessage());
                e.printStackTrace();
            }

        } else {
            ConnectionManager.INSTANCE.remove(socketEndpoint);
            LogUtil.err("send msg session is close ,ws=" + socketEndpoint);
        }

        return false;
    }

    public static void send(Set<Session> sessions, MMessage message) {
        for (Session s : sessions) {
            send(s, message);
        }
    }
}
